package com.atguigu.tingshu.order.task;

import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.order.service.OrderInfoService;
import com.atguigu.tingshu.vo.order.OrderInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBlockingQueue;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

@Component
@Slf4j
public class RedisDelayHandle {

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private OrderInfoService orderInfoService;

    @Scheduled(cron = "0/1 * * * * ?")
    public void orderCancelDelayQueueHandle(){
        //采用分布式锁
        RLock lock = redissonClient.getLock(RedisConstant.DELAY_QUEUE_ORDER_LOCK);
        //获取分布式锁
        boolean tryLock = lock.tryLock();
        //分布式锁存在
        if(tryLock){
            try {
                //从redissonClient中获取延迟队列
                RBlockingQueue<String> blockingQueue = redissonClient.getBlockingQueue(RedisConstant.DELAY_QUEUE_ORDER_CANCEL);
                String orderNo = blockingQueue.poll();
                if (!StringUtils.isEmpty(orderNo)){
                    //执行订单取消
                    orderInfoService.canalOrder(orderNo);
                }
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                //释放锁
                lock.unlock();
            }

        }

    }

}
